package com.sven.idrivingfutureserver.exception;

import cn.dev33.satoken.exception.SaTokenException;
import com.google.common.collect.ImmutableMap;
import com.sven.idrivingfutureserver.common.CommonCode;
import com.sven.idrivingfutureserver.common.Response;
import com.sven.idrivingfutureserver.common.RestResponse;
import com.sven.idrivingfutureserver.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //定义map，配置异常类型所对应的错误代码
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;

    //定义map的builder对象，去构建ImmutableMap
    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();

    /**
     * 处理Sa-Token抛出的异常
     * 异常码参考：https://sa-token.cc/doc.html#/fun/exception-code
     */
    @ExceptionHandler(SaTokenException.class)
    public Response handleBindException(HttpServletRequest request, SaTokenException e) {
        e.printStackTrace();
        recordLog(request, e);
        switch (e.getCode()) {
            case 11011: //未能读取到有效Token
            case 11012: //Token无效
            case 11013: //Token已过期
                return new Response(CommonCode.NOT_LOGIN_ERROR);
            case 11041: //缺少指定的角色
            case 11051: //缺少指定的权限
                return new Response(CommonCode.NOT_PERMISSION_ERROR);
            case 11014: //Token已被顶下线
                return new Response(CommonCode.FORCE_LOGOUT_ERROR);
            case 11015: //Token已被踢下线
                return new Response(CommonCode.KICK_OUT_ERROR);
            default:
                return Response.FAIL();
        }
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Response handlerMissingServletRequestParameterException(HttpServletRequest request, MissingServletRequestParameterException e) {
        e.printStackTrace();
        recordLog(request, e);
        final CommonCode missingError = CommonCode.PARAM_MISSING_ERROR;
        missingError.setMessage("接口参数缺失：" + e.getMessage());
        return new Response(missingError);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Response handleBindException(HttpServletRequest request, BindException bindException) {
        bindException.printStackTrace();
        recordLog(request, bindException);
        final CommonCode bindingError = CommonCode.BINDING_ERROR;
        bindingError.setMessage("参数绑定异常: " + bindException.getAllErrors().get(0).getDefaultMessage());
        return new Response(bindingError);
    }

    @ExceptionHandler(BaseException.class)
    public Response handleBaseException(HttpServletRequest request, BaseException baseException) {
        baseException.printStackTrace();
        recordLog(request, baseException);
        return new Response(baseException.getResultCode());
    }

    @ExceptionHandler(RestException.class)
    public Response handleBaseException(HttpServletRequest request, RestException restException) {
        restException.printStackTrace();
        recordLog(request, restException);
        return new RestResponse<Object>(restException.getResultCode(), restException.errorData);
    }

    @ExceptionHandler(Exception.class)
    public Response handleException(HttpServletRequest request, Exception exception) {
        exception.printStackTrace();
        recordLog(request, exception);
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode != null) {
            return new Response(resultCode);
        } else {
            return new Response(CommonCode.SERVER_ERROR);
        }

    }

    private void recordLog(HttpServletRequest request, Exception e) {
        log.error("catch exception ：{}, msg: {} HTTP method: {}, URL: {}",
                e.getClass().getName(), e.getMessage(), request.getMethod(), getUrl(request));
    }

    private String getUrl(HttpServletRequest req) {
        String reqUrl = req.getRequestURL().toString();
        final String queryString = req.getQueryString();
        if (queryString != null) {
            reqUrl += "?" + queryString;
        }
        return reqUrl;
    }


    static {
        //定义异常类型所对应的错误代码 可以在各微服务定义各自需要捕获的异常类型
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
    }
}
